package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.QuestionDao;
import com.itheima.dao.QuestionItemDao;
import com.itheima.domain.Question;
import com.itheima.service.QuestionService;
import com.itheima.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.Date;
import java.util.List;
import java.util.UUID;

public class QuestionServiceImpl implements QuestionService {
    @Override
    public PageInfo findByPage(int currentPage) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        QuestionDao mapper = sqlSession.getMapper(QuestionDao.class);
        PageHelper.startPage(currentPage,5);
        List<Question> list = mapper.findAll();
        PageInfo pageInfo = new PageInfo(list);
        sqlSession.close();
        return pageInfo;
    }

    @Override
    public void add(Question question) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        QuestionDao mapper = sqlSession.getMapper(QuestionDao.class);
        String id = UUID.randomUUID().toString();
        question.setCreateTime(new Date());
        question.setId(id);
        mapper.add(question);
        sqlSession.close();
    }

    @Override
    public void update(Question question) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        QuestionDao mapper = sqlSession.getMapper(QuestionDao.class);
        mapper.update(question);
        sqlSession.close();
    }

    @Override
    public void delete(String id) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        QuestionDao mapper = sqlSession.getMapper(QuestionDao.class);
        QuestionItemDao mapper1 = sqlSession.getMapper(QuestionItemDao.class);
        mapper1.delete(id);
        mapper.delete(id);
        sqlSession.close();
    }
}
